const loginInp = document.querySelector('.login')
const userInp = document.querySelector('.user')
const pwdInp = document.querySelector('.pwd')
const errInp = document.querySelector('.err')
const userErrInp = document.querySelector('.userErr')
const pwdErrrInp = document.querySelector('.pwdErr')

loginInp.addEventListener('click',() => {
  const user = userInp.value
  const pwd = pwdInp.value

  if(!user) {
    userErrInp.style.display = 'inline'
  } else {
    userErrInp.style.display = 'none'
  }
  if(!pwd) {
    pwdErrrInp.style.display = 'inline'
  } else {
    pwdErrrInp.style.display = 'none'
  }

  const xhr = new XMLHttpRequest()
  xhr.open('POST','http://localhost:8888/users/login')
  xhr.onloadend = function () {
    const res = JSON.parse(xhr.responseText)
    console.log(res)
    loginHandler(res)
  }
  xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
  xhr.send(`username=${ user }&password=${ pwd }`)
})

function loginHandler(res) {
  if (res.code === 0) {
    errInp.style.display = 'inline'
  }
  if (res.code === 1) {
    window.localStorage.setItem('token', res.token)
    window.localStorage.setItem('id', res.user.id)
    window.location.href = './index.html'
  }
}